<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">

<head>
    <th:block th:include="common/head::head"></th:block>
    <link th:href="@{${session.jpomProxyPath}+'/static/xterm/xterm.min.css?v='+${session.staticCacheTime}}"
          rel="stylesheet" type="text/css"/>
    <script th:src="@{${session.jpomProxyPath}+'/static/xterm/xterm.min.js?v='+${session.staticCacheTime}}"></script>
    <style>

    </style>
</head>

<body onbeforeunload="goodbye()">
<div id="terminal"></div>
</body>
<script type="text/javascript">
    var term;
    var sock;
    //  tail 文件
    var tail = getQueryString("tail");
    var zip = getQueryString("zip");
    var gz = getQueryString("gz");
    var cursorBlink = !tail;
    var cursorBlinkZip = !zip;
    var cursorBlinkGz  = !gz;

    function loadSuccess() {
        top.layer.load({
            icon: 16,
            shade: 0.2,
            time: 1000 * 30,
            end: function () {
                top.location.reload();
            }
        });
        if (zip !== null){
            var url = getSocketHost() + "/ssh?userId=[[${session.user.getUserMd5Key()}]]&" +
                "sshId=[[${item?.id}]]&nodeId=system&type=ssh&" +
                "zip=" + zip;
        } else if (gz !== null){
            var url = getSocketHost() + "/ssh?userId=[[${session.user.getUserMd5Key()}]]&" +
                "sshId=[[${item?.id}]]&nodeId=system&type=ssh&" +
                "gz=" + gz;
        }else {
            var url = getSocketHost() + "/ssh?userId=[[${session.user.getUserMd5Key()}]]&" +
                "sshId=[[${item?.id}]]&nodeId=system&type=ssh&" +
                "tail=" + tail;
        }
        var terminal = document.getElementById("#terminal");
        term = new window.Terminal({
            cursorBlink: cursorBlink,
            cursorBlinkGz: cursorBlinkGz,
            cursorBlinkZip: cursorBlinkZip,
        });
        //
        term.onData(function (data) {
            if (tail || zip || gz) {
                return;
            }
            sock.send(JSON.stringify({'data': data}));
        });

        // 监听按键
        var startX = 2;
        term.onKey(function (key) {
            if (tail || zip || gz) {
                return;
            }
            var ev = key.domEvent;
            // const printable = !ev.altKey && !ev.altGraphKey && !ev.ctrlKey && !ev.metaKey;
            if (ev.keyCode === 8) {
                // Do not delete the prompt
                if (term._core.buffer.x > startX) {
                    term.write('\b \b');
                }
            }
        });
        sock = new WebSocket(url);
        //
        sock.onopen = function () {
            term.open(terminal, true);
            top.layer.closeAll();
            setTimeout(function () {
                startX = term._core.buffer.x;
                // console.log();
            }, 2000);
        };

        sock.onmessage = function (msg) {
            var reader = new window.FileReader();

            reader.onloadend = function () {
                var decoder = new window.TextDecoder();
                var text = decoder.decode(reader.result);
                // console.log(text);
                term.write(text);
                if (!term.resized) {
                    resize_term(term, sock);
                    term.resized = true;
                }
            };
            reader.onerror = function (e) {
                layer.msg("解析数据异常");
            };
            reader.readAsArrayBuffer(msg.data);
        };

        sock.onerror = function (e) {
            console.error(e);
            layer.msg("连接异常");
        };
        sock.onclose = function (e) {
            console.error(e);
            if (term) {
                term.destroy();
            }
            term = null;
            sock = null;
            layer.msg("连接已经关闭：" + e.code);
        };

        $(window).resize(function () {
            if (term && sock) {
                resize_term(term, sock);
            }
        });
    }

    function resize_term(term, sock) {
        var style = {
            width: term._core.charMeasure.width,
            height: term._core.charMeasure.height
        };

        var cols = parseInt((window.innerWidth) / style.width, 10);
        var rows = parseInt((window.innerHeight * 0.95) / style.height, 10);
        var geometry = {cols: cols, rows: rows};
        term.resize(geometry.cols, geometry.rows);
        sock.send(JSON.stringify({'resize': geometry}));
    }

    window.onbeforeunload = function (e) {
        goodbye();
    };

    window.onunload = function () {
        goodbye();
    };

    function goodbye() {
        if (sock) {
            sock.close();
            sock = null;
            term = null;
        }
    }

</script>
</html>